// IMPORTANT: this is a plugin which requires jQuery for initialisation and data manipulation

import {
    Component,
    OnInit,
    OnChanges,
    AfterViewInit,
    SimpleChanges
} from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Http } from '@angular/http';
import { BaseComponet } from '../BaseComponet';
declare const $: any;
export let isSubmitingConfig: Boolean = false;
interface FileReaderEventTarget extends EventTarget {
    result: string;
}

interface FileReaderEvent extends Event {
    target: FileReaderEventTarget;
    getMessage(): string;
}
@Component({
    selector: 'app-wizard-cmp',
    templateUrl: 'wizard.component.html',
    styleUrls: ['./wizard.component.css']
})
export class WizardComponent extends BaseComponet
    implements OnInit, OnChanges, AfterViewInit {
    // users
    public checkedUserIds: any[] = [];
    public checkedAllUsers: Boolean = false;
    public searchUsersKeywords: String = '';
    public usersOrderBy: String = '';
    public usersOrderType: String = '';
    public usersPageNo: Number = 1;
    public usersPageSize: Number = 10;
    public users: any[] = [];
    public usersTotal: Number;
    public usersTotalPages: Number;
    public selectedUsers: any[] = [];
    // org
    public searchOrgsKeywords: String = '';
    public orgsOrderBy: String = '';
    public orgsOrderType: String = '';
    public orgsPageNo: Number = 1;
    public orgsPageSize: Number = 10;
    public orgs: any[] = [];
    public orgsTotal: Number;
    public orgsTotalPages: Number;
    public selectedOrg: any = null;
    public orgSubLinks: any[];
    public orgId: String;
    public parentOrgId: String;
    // position
    public searchPositionsKeywords: String = '';
    public positionsOrderBy: String = '';
    public positionsOrderType: String = '';
    public positionsPageNo: Number = 1;
    public positionsPageSize: Number = 10;
    public positions: any[] = [];
    public positionsTotal: Number;
    public positionsTotalPages: Number;
    public selectedPosition: any = null;
    // roles
    public checkedRoleIds: any[] = [];
    public checkedAllRoles: Boolean = false;
    public searchRolesKeywords: String = '';
    public rolesOrderBy: String = '';
    public rolesOrderType: String = '';
    public rolesPageNo: Number = 1;
    public rolesPageSize: Number = 10;
    public roles: any[] = [];
    public rolesTotal: Number;
    public rolesTotalPages: Number;
    public selectedRoles: any[] = [];
    public roleSubLinks: any[];
    public roleId: String;
    public parentRoleId: String;

    public wizard: any;
    constructor(
        public routerInfo: ActivatedRoute,
        public http: Http,
        public router: Router
    ) {
        super();
    }
    ngOnInit() {
        this.hideLoading();
        isSubmitingConfig = false;
        $('[data-toggle="popover"]').popover();
        const usersPageSize = parseInt(
            localStorage.getItem('wizard-usersPageSize'),
            10
        );
        if (usersPageSize == null || isNaN(usersPageSize)) {
            this.usersPageSize = 10;
        } else {
            this.usersPageSize = usersPageSize;
        }
        localStorage.setItem('wizard-usersPageSize', '' + this.usersPageSize);
        const orgsPageSize = parseInt(
            localStorage.getItem('wizard-orgsPageSize'),
            10
        );
        if (orgsPageSize == null || isNaN(orgsPageSize)) {
            this.orgsPageSize = 10;
        } else {
            this.orgsPageSize = orgsPageSize;
        }
        localStorage.setItem('wizard-orgsPageSize', '' + this.orgsPageSize);
        const positionsPageSize = parseInt(
            localStorage.getItem('wizard-positionsPageSize'),
            10
        );
        if (positionsPageSize == null || isNaN(positionsPageSize)) {
            this.positionsPageSize = 10;
        } else {
            this.positionsPageSize = positionsPageSize;
        }
        localStorage.setItem(
            'wizard-positionsPageSize',
            '' + this.positionsPageSize
        );
        const rolesPageSize = parseInt(
            localStorage.getItem('wizard-rolesPageSize'),
            10
        );
        if (rolesPageSize == null || isNaN(rolesPageSize)) {
            this.rolesPageSize = 10;
        } else {
            this.rolesPageSize = rolesPageSize;
        }
        localStorage.setItem('wizard-rolesPageSize', '' + this.rolesPageSize);
        this.displayUsersData();
        this.displayOrgsData();
        this.displayPositionsData();
        this.displayRolesData();
        // Code for the Validator
        const $validator = $('.wizard-card form').validate({
            rules: {
                firstname: {
                    required: true,
                    minlength: 3
                },
                lastname: {
                    required: true,
                    minlength: 3
                },
                email: {
                    required: true,
                    minlength: 3
                }
            },

            errorPlacement: function(error: any, element: any) {
                $(element)
                    .parent('div')
                    .addClass('has-error');
            }
        });
        // Wizard Initialization
        this.wizard = $('#wizardConfig').bootstrapWizard({
            tabClass: 'nav nav-pills',
            nextSelector: '.btn-next',
            previousSelector: '.btn-previous',
            onPrevious: function(tab, navigation, index) {
                return !isSubmitingConfig;
            },
            onNext: function(tab, navigation, index) {
                // var $valid = $('.wizard-card form').valid();
                // if (!$valid) {
                //     $validator.focusInvalid();
                //     return false;
                // }
            },

            onInit: function(tab: any, navigation: any, index: any) {
                // check number of tabs and fill the entire row
                let $total = navigation.find('li').length;
                let $wizard = navigation.closest('.wizard-card');

                let $first_li = navigation.find('li:first-child a').html();
                let $moving_div = $(
                    '<div class="moving-tab">' + $first_li + '</div>'
                );
                $('.wizard-card .wizard-navigation').append($moving_div);

                $total = $wizard.find('.nav li').length;
                let $li_width = 100 / $total;

                let total_steps = $wizard.find('.nav li').length;
                let move_distance = $wizard.width() / total_steps;
                let index_temp = index;
                let vertical_level = 0;

                let mobile_device = $(document).width() < 600 && $total > 3;

                if (mobile_device) {
                    move_distance = $wizard.width() / 2;
                    index_temp = index % 2;
                    $li_width = 50;
                }

                $wizard.find('.nav li').css('width', $li_width + '%');

                let step_width = move_distance;
                move_distance = move_distance * index_temp;

                let $current = index + 1;

                if (
                    $current == 1 ||
                    (mobile_device == true && index % 2 == 0)
                ) {
                    move_distance -= 8;
                } else if (
                    $current == total_steps ||
                    (mobile_device == true && index % 2 == 1)
                ) {
                    move_distance += 8;
                }

                if (mobile_device) {
                    let x: any = index / 2;
                    vertical_level = parseInt(x);
                    vertical_level = vertical_level * 38;
                }

                $wizard.find('.moving-tab').css('width', step_width);
                $('.moving-tab').css({
                    transform:
                        'translate3d(' +
                        move_distance +
                        'px, ' +
                        vertical_level +
                        'px, 0)',
                    transition: 'all 0.5s cubic-bezier(0.29, 1.42, 0.79, 1)'
                });
                $('.moving-tab').css('transition', 'transform 0s');
            },

            onTabClick: function(tab: any, navigation: any, index: any) {
                return !isSubmitingConfig;
                // const $valid = $('.wizard-card form').valid();

                // if (!$valid) {
                //     return false;
                // } else {
                //     return true;
                // }
            },

            onTabShow: function(tab: any, navigation: any, index: any) {
                let $total = navigation.find('li').length;
                let $current = index + 1;

                const $wizard = navigation.closest('.wizard-card');

                // If it's the last tab then hide the last button and show the finish instead
                if ($current >= $total) {
                    $($wizard)
                        .find('.btn-next')
                        .hide();
                    $($wizard)
                        .find('.btn-finish')
                        .show();
                } else {
                    $($wizard)
                        .find('.btn-next')
                        .show();
                    $($wizard)
                        .find('.btn-finish')
                        .hide();
                }

                const button_text = navigation
                    .find('li:nth-child(' + $current + ') a')
                    .html();

                setTimeout(function() {
                    $('.moving-tab').text(button_text);
                }, 150);

                const checkbox = $('.footer-checkbox');

                if (index !== 0) {
                    $(checkbox).css({
                        opacity: '0',
                        visibility: 'hidden',
                        position: 'absolute'
                    });
                } else {
                    $(checkbox).css({
                        opacity: '1',
                        visibility: 'visible'
                    });
                }
                $total = $wizard.find('.nav li').length;
                let $li_width = 100 / $total;

                let total_steps = $wizard.find('.nav li').length;
                let move_distance = $wizard.width() / total_steps;
                let index_temp = index;
                let vertical_level = 0;

                let mobile_device = $(document).width() < 600 && $total > 3;

                if (mobile_device) {
                    move_distance = $wizard.width() / 2;
                    index_temp = index % 2;
                    $li_width = 50;
                }

                $wizard.find('.nav li').css('width', $li_width + '%');

                let step_width = move_distance;
                move_distance = move_distance * index_temp;

                $current = index + 1;

                if (
                    $current == 1 ||
                    (mobile_device == true && index % 2 == 0)
                ) {
                    move_distance -= 8;
                } else if (
                    $current == total_steps ||
                    (mobile_device == true && index % 2 == 1)
                ) {
                    move_distance += 8;
                }

                if (mobile_device) {
                    let x: any = index / 2;
                    vertical_level = parseInt(x);
                    vertical_level = vertical_level * 38;
                }

                $wizard.find('.moving-tab').css('width', step_width);
                $('.moving-tab').css({
                    transform:
                        'translate3d(' +
                        move_distance +
                        'px, ' +
                        vertical_level +
                        'px, 0)',
                    transition: 'all 0.5s cubic-bezier(0.29, 1.42, 0.79, 1)'
                });
            }
        });

        // Prepare the preview for profile picture
        $('#wizard-picture').change(function() {
            const input = $(this);

            if (input[0].files && input[0].files[0]) {
                const reader = new FileReader();

                reader.onload = function(e: FileReaderEvent) {
                    $('#wizardPicturePreview')
                        .attr('src', e.target.result)
                        .fadeIn('slow');
                };
                reader.readAsDataURL(input[0].files[0]);
            }
        });

        $('[data-toggle="wizard-radio"]').click(function() {
            const wizard = $(this).closest('.wizard-card');
            wizard.find('[data-toggle="wizard-radio"]').removeClass('active');
            $(this).addClass('active');
            $(wizard)
                .find('[type="radio"]')
                .removeAttr('checked');
            $(this)
                .find('[type="radio"]')
                .attr('checked', 'true');
        });

        $('[data-toggle="wizard-checkbox"]').click(function() {
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
                $(this)
                    .find('[type="checkbox"]')
                    .removeAttr('checked');
            } else {
                $(this).addClass('active');
                $(this)
                    .find('[type="checkbox"]')
                    .attr('checked', 'true');
            }
        });

        $('.set-full-height').css('height', 'auto');
    }

    ngOnChanges(changes: SimpleChanges) {
        const input = $(this);

        if (input[0].files && input[0].files[0]) {
            const reader: any = new FileReader();

            reader.onload = function(e: FileReaderEvent) {
                $('#wizardPicturePreview')
                    .attr('src', e.target.result)
                    .fadeIn('slow');
            };
            reader.readAsDataURL(input[0].files[0]);
        }
    }
    ngAfterViewInit() {
        $(window).resize(() => {
            $('.wizard-card').each(function() {
                const $wizard = $(this);
                const index = $wizard.bootstrapWizard('currentIndex');
                let $total = $wizard.find('.nav li').length;
                let $li_width = 100 / $total;

                let total_steps = $wizard.find('.nav li').length;
                let move_distance = $wizard.width() / total_steps;
                let index_temp = index;
                let vertical_level = 0;

                let mobile_device = $(document).width() < 600 && $total > 3;

                if (mobile_device) {
                    move_distance = $wizard.width() / 2;
                    index_temp = index % 2;
                    $li_width = 50;
                }

                $wizard.find('.nav li').css('width', $li_width + '%');

                let step_width = move_distance;
                move_distance = move_distance * index_temp;

                let $current = index + 1;

                if (
                    $current == 1 ||
                    (mobile_device == true && index % 2 == 0)
                ) {
                    move_distance -= 8;
                } else if (
                    $current == total_steps ||
                    (mobile_device == true && index % 2 == 1)
                ) {
                    move_distance += 8;
                }

                if (mobile_device) {
                    let x: any = index / 2;
                    vertical_level = parseInt(x);
                    vertical_level = vertical_level * 38;
                }

                $wizard.find('.moving-tab').css('width', step_width);
                $('.moving-tab').css({
                    transform:
                        'translate3d(' +
                        move_distance +
                        'px, ' +
                        vertical_level +
                        'px, 0)',
                    transition: 'all 0.5s cubic-bezier(0.29, 1.42, 0.79, 1)'
                });

                $('.moving-tab').css({
                    transition: 'transform 0s'
                });
            });
        });
    }
    displayUsersData() {
        this.checkedUserIds = [];
        this.checkedAllUsers = false;
        $('#loadingUsers').show();
        this.http
            .get(
                '/user/back/user/page' +
                    '/search-' +
                    this.searchUsersKeywords.toString() +
                    '/order-by-' +
                    this.usersOrderBy +
                    '/order-type-' +
                    this.usersOrderType +
                    '/page-no/' +
                    this.usersPageNo +
                    '/page-size/' +
                    this.usersPageSize
            )
            .map(result => result.json())
            .subscribe(
                result => {
                    $('#loadingUsers').hide();
                    this.users = result.list;
                    this.usersTotal = result.total;
                    this.usersTotalPages = result.totalPages;
                    this.usersOrderBy = result.orderBy;
                    this.usersOrderType = result.orderType;
                },
                error => {}
            );
    }
    sortUsers(orderBy) {
        if (this.usersOrderBy === orderBy) {
            if (this.usersOrderType === 'asc') {
                this.usersOrderType = 'desc';
            } else {
                this.usersOrderType = 'asc';
            }
        } else {
            this.usersOrderBy = orderBy;
        }
        this.displayUsersData();
    }
    clearUsersKeywords() {
        this.searchUsersKeywords = '';
    }
    setUsersPageSize(pageSize) {
        this.usersPageNo = 1;
        this.usersPageSize = pageSize;
        localStorage.setItem('wizard-usersPageSize', '' + this.usersPageSize);
        this.displayUsersData();
    }
    goToUsersPage(pageNo) {
        this.usersPageNo = pageNo;
        this.displayUsersData();
    }
    checkAllUsers() {
        if (this.checkedAllUsers === false) {
            this.checkedAllUsers = true;
            this.checkedUserIds = [];
            for (let i = 0; i < this.users.length; i++) {
                this.checkedUserIds.push(this.users[i].userId);
            }
            $('.user-list').prop('checked', true);
        } else {
            this.checkedAllUsers = false;
            this.checkedUserIds = [];
            $('.user-list').prop('checked', false);
        }
    }
    checkUser(userId) {
        this.checkedUserIds = [];
        if ($('.user-list').length === $('.user-list:checked').length) {
            this.checkedAllUsers = true;
        } else {
            this.checkedAllUsers = false;
        }
        const checkedUserIds = this.checkedUserIds;
        $('.user-list:checked').each(function() {
            checkedUserIds.push($(this).val());
        });
    }
    selectUsers() {
        for (let i = 0; i < this.checkedUserIds.length; i++) {
            let found = false;
            for (let j = 0; j < this.selectedUsers.length; j++) {
                if (this.selectedUsers[j].userId === this.checkedUserIds[i]) {
                    found = true;
                    break;
                }
            }
            if (found === false) {
                for (let j = 0; j < this.users.length; j++) {
                    if (this.users[j].userId === this.checkedUserIds[i]) {
                        this.selectedUsers.push(this.users[j]);
                        break;
                    }
                }
            }
        }
        $('.user-list').prop('checked', false);
        this.checkedAllUsers = false;
        this.checkedUserIds = [];
    }
    unselectUser(userId) {
        const tempUsers: any[] = [];
        for (let j = 0; j < this.selectedUsers.length; j++) {
            if (this.selectedUsers[j].userId != userId) {
                tempUsers.push(this.selectedUsers[j]);
            }
        }
        this.selectedUsers = tempUsers;
    }
    displayOrgsData() {
        $('#loadingOrgs').show();
        if (this.orgId == null || this.orgId === '' || this.orgId === '-1') {
            this.orgId = '-1';
            this.parentOrgId = null;
            this.orgSubLinks = [];
            this.orgSubLinks[0] = {
                orgId: '',
                orgName: '所有组织机构'
            };
            this.http
                .get(
                    '/user/back/org/page/parent-id--1/search-' +
                        this.searchOrgsKeywords.toString() +
                        '/order-by-' +
                        this.orgsOrderBy +
                        '/order-type-' +
                        this.orgsOrderType +
                        '/page-no/' +
                        this.orgsPageNo +
                        '/page-size/' +
                        this.orgsPageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        $('#loadingOrgs').hide();
                        this.orgsTotal = result.total;
                        this.orgs = result.list;
                        this.orgsTotalPages = result.totalPages;
                        this.orgsOrderBy = result.orderBy;
                        this.orgsOrderType = result.orderType;
                    },
                    error => {}
                );
        } else {
            this.http
                .get('/user/back/org/path/' + this.orgId)
                .map(result => result.json())
                .subscribe(
                    result => {
                        this.orgSubLinks = result.orgPath;
                        if (this.orgSubLinks.length > 1) {
                            this.parentOrgId = this.orgSubLinks[
                                this.orgSubLinks.length - 2
                            ].orgId;
                        } else if (this.orgSubLinks.length > 0) {
                            this.parentOrgId = '-1';
                        } else {
                            this.parentOrgId = null;
                        }
                        this.orgSubLinks.unshift({
                            orgId: '',
                            orgName: '所有组织机构'
                        });
                    },
                    error => {}
                );
            this.http
                .get(
                    '/user/back/org/page/parent-id-' +
                        this.orgId +
                        '/search-' +
                        this.searchOrgsKeywords.toString() +
                        '/order-by-' +
                        this.orgsOrderBy +
                        '/order-type-' +
                        this.orgsOrderType +
                        '/page-no/' +
                        this.orgsPageNo +
                        '/page-size/' +
                        this.orgsPageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        $('#loadingOrgs').hide();
                        this.orgsTotal = result.total;
                        this.orgs = result.list;
                        this.orgsTotalPages = result.totalPages;
                        this.orgsOrderBy = result.orderBy;
                        this.orgsOrderType = result.orderType;
                    },
                    error => {}
                );
        }
    }
    upToParentOrg(parentId) {
        if (parentId == null) {
            alert('已经到达最上级');
            return;
        }
        this.orgId = parentId;
        this.orgsPageNo = 1;
        this.displayOrgsData();
    }
    gotoOrg(orgId) {
        this.orgId = orgId;
        this.orgsPageNo = 1;
        this.displayOrgsData();
    }
    sortOrgs(orderBy) {
        if (this.orgsOrderBy === orderBy) {
            if (this.orgsOrderType === 'asc') {
                this.orgsOrderType = 'desc';
            } else {
                this.orgsOrderType = 'asc';
            }
        } else {
            this.orgsOrderBy = orderBy;
        }
        this.displayOrgsData();
    }
    clearOrgsKeywords() {
        this.searchOrgsKeywords = '';
    }
    setOrgsPageSize(pageSize) {
        this.orgsPageNo = 1;
        this.orgsPageSize = pageSize;
        localStorage.setItem('wizard-orgsPageSize', '' + this.orgsPageSize);
        this.displayOrgsData();
    }
    goToOrgsPage(pageNo) {
        this.orgsPageNo = pageNo;
        this.displayOrgsData();
    }
    selectOrg() {
        const orgId = $('.org-list:checked')
            .eq(0)
            .val();
        for (let j = 0; j < this.orgs.length; j++) {
            if (this.orgs[j].orgId === orgId) {
                this.selectedOrg = this.orgs[j];
                break;
            }
        }
    }
    unselectOrg() {
        this.selectedOrg = null;
        $('.org-list').prop('checked', false);
    }
    displayPositionsData() {
        $('#loadingPositions').show();
        this.http
            .get(
                '/user/back/position/page' +
                    '/search-' +
                    this.searchPositionsKeywords.toString() +
                    '/order-by-' +
                    this.positionsOrderBy +
                    '/order-type-' +
                    this.positionsOrderType +
                    '/page-no/' +
                    this.positionsPageNo +
                    '/page-size/' +
                    this.positionsPageSize
            )
            .map(result => result.json())
            .subscribe(
                result => {
                    $('#loadingPositions').hide();
                    this.positions = result.list;
                    this.positionsTotal = result.total;
                    this.positionsTotalPages = result.totalPages;
                    this.positionsOrderBy = result.orderBy;
                    this.positionsOrderType = result.orderType;
                },
                error => {}
            );
    }
    sortPositions(orderBy) {
        if (this.positionsOrderBy === orderBy) {
            if (this.positionsOrderType === 'asc') {
                this.positionsOrderType = 'desc';
            } else {
                this.positionsOrderType = 'asc';
            }
        } else {
            this.positionsOrderBy = orderBy;
        }
        this.displayPositionsData();
    }
    clearPositionsKeywords() {
        this.searchPositionsKeywords = '';
    }
    setPositionsPageSize(pageSize) {
        this.positionsPageNo = 1;
        this.positionsPageSize = pageSize;
        localStorage.setItem(
            'wizard-positionsPageSize',
            '' + this.positionsPageSize
        );
        this.displayPositionsData();
    }
    goToPositionsPage(pageNo) {
        this.positionsPageNo = pageNo;
        this.displayPositionsData();
    }
    selectPosition() {
        const positionId = $('.position-list:checked')
            .eq(0)
            .val();
        for (let j = 0; j < this.positions.length; j++) {
            if (this.positions[j].positionId === positionId) {
                this.selectedPosition = this.positions[j];
                break;
            }
        }
    }
    unselectPosition() {
        this.selectedPosition = null;
        $('.position-list').prop('checked', false);
    }
    displayRolesData() {
        this.checkedRoleIds = [];
        this.checkedAllRoles = false;
        $('#loadingRoles').show();
        if (this.roleId == null || this.roleId === '' || this.roleId === '-1') {
            this.roleId = '-1';
            this.parentRoleId = null;
            this.roleSubLinks = [];
            this.roleSubLinks[0] = {
                roleId: '',
                roleName: '所有角色'
            };
            this.http
                .get(
                    '/user/back/role/page/parent-id--1/search-' +
                        this.searchRolesKeywords.toString() +
                        '/order-by-' +
                        this.rolesOrderBy +
                        '/order-type-' +
                        this.rolesOrderType +
                        '/page-no/' +
                        this.rolesPageNo +
                        '/page-size/' +
                        this.rolesPageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        $('#loadingRoles').hide();
                        this.rolesTotal = result.total;
                        this.roles = result.list;
                        this.rolesTotalPages = result.totalPages;
                        this.rolesOrderBy = result.orderBy;
                        this.rolesOrderType = result.orderType;
                    },
                    error => {}
                );
        } else {
            this.http
                .get('/user/back/role/path/' + this.roleId)
                .map(result => result.json())
                .subscribe(
                    result => {
                        this.roleSubLinks = result.rolePath;
                        if (this.roleSubLinks.length > 1) {
                            this.parentRoleId = this.roleSubLinks[
                                this.roleSubLinks.length - 2
                            ].roleId;
                        } else if (this.roleSubLinks.length > 0) {
                            this.parentRoleId = '-1';
                        } else {
                            this.parentRoleId = null;
                        }
                        this.roleSubLinks.unshift({
                            roleId: '',
                            roleName: '所有角色'
                        });
                    },
                    error => {}
                );
            this.http
                .get(
                    '/user/back/role/page/parent-id-' +
                        this.roleId +
                        '/search-' +
                        this.searchRolesKeywords.toString() +
                        '/order-by-' +
                        this.rolesOrderBy +
                        '/order-type-' +
                        this.rolesOrderType +
                        '/page-no/' +
                        this.rolesPageNo +
                        '/page-size/' +
                        this.rolesPageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        $('#loadingRoles').hide();
                        this.rolesTotal = result.total;
                        this.roles = result.list;
                        this.rolesTotalPages = result.totalPages;
                        this.rolesOrderBy = result.orderBy;
                        this.rolesOrderType = result.orderType;
                    },
                    error => {}
                );
        }
    }
    upToParentRole(parentId) {
        if (parentId == null) {
            alert('已经到达最上级');
            return;
        }
        this.roleId = parentId;
        this.rolesPageNo = 1;
        this.displayRolesData();
    }
    gotoRole(roleId) {
        this.roleId = roleId;
        this.rolesPageNo = 1;
        this.displayRolesData();
    }
    sortRoles(orderBy) {
        if (this.rolesOrderBy === orderBy) {
            if (this.rolesOrderType === 'asc') {
                this.rolesOrderType = 'desc';
            } else {
                this.rolesOrderType = 'asc';
            }
        } else {
            this.rolesOrderBy = orderBy;
        }
        this.displayRolesData();
    }
    clearRolesKeywords() {
        this.searchRolesKeywords = '';
    }
    setRolesPageSize(pageSize) {
        this.rolesPageNo = 1;
        this.rolesPageSize = pageSize;
        localStorage.setItem('wizard-rolesPageSize', '' + this.rolesPageSize);
        this.displayRolesData();
    }
    goToRolesPage(pageNo) {
        this.rolesPageNo = pageNo;
        this.displayRolesData();
    }
    checkRole(roleId) {
        this.checkedRoleIds = [];
        if ($('.role-list').length === $('.role-list:checked').length) {
            this.checkedAllRoles = true;
        } else {
            this.checkedAllRoles = false;
        }
        const checkedRoleIds = this.checkedRoleIds;
        $('.role-list:checked').each(function() {
            checkedRoleIds.push($(this).val());
        });
    }
    checkAllRoles() {
        this.checkedRoleIds = [];
        const checkedRoleIds = this.checkedRoleIds;
        if (this.checkedAllRoles) {
            $('.role-list').attr('checked');
            $('.role-list:checked').each(function() {
                checkedRoleIds.push($(this).val());
            });
        } else {
            $('.role-list').removeAttr('checked');
        }
    }
    selectRoles() {
        for (let i = 0; i < this.checkedRoleIds.length; i++) {
            let found = false;
            for (let j = 0; j < this.selectedRoles.length; j++) {
                if (this.selectedRoles[j].roleId === this.checkedRoleIds[i]) {
                    found = true;
                    break;
                }
            }
            if (found === false) {
                for (let j = 0; j < this.roles.length; j++) {
                    if (this.roles[j].roleId === this.checkedRoleIds[i]) {
                        this.selectedRoles.push(this.roles[j]);
                        break;
                    }
                }
            }
        }
        $('.role-list').prop('checked', false);
        this.checkedAllRoles = false;
        this.checkedRoleIds = [];
    }
    unselectRole(roleId) {
        const tempRoles: any[] = [];
        for (let j = 0; j < this.selectedRoles.length; j++) {
            if (this.selectedRoles[j].roleId != roleId) {
                tempRoles.push(this.selectedRoles[j]);
            }
        }
        this.selectedRoles = tempRoles;
    }
    goToStep(index) {
        this.wizard.bootstrapWizard('show', index);
    }
    submitConfig() {
        if (this.selectedUsers.length === 0) {
            alert('请选择需要配置的帐号');
            return;
        }
        if (!this.selectedOrg) {
            alert('请选择指派机构');
            return;
        }
        if (!this.selectedPosition) {
            alert('选择指派职位');
            return;
        }
        if (this.selectedRoles.length === 0) {
            alert('请选择指派角色');
            return;
        }
        const groupId = this.selectedOrg.groupId;
        if (groupId !== this.selectedPosition.groupId) {
            if (confirm('职位和机构不属于同一个集团，是否继续？') === false) {
                return;
            }
        }
        for (let i = 0; i < this.selectedRoles.length; i++) {
            console.log(groupId, this.selectedRoles[i]);
            if (groupId !== this.selectedRoles[i].groupId) {
                if (
                    confirm(
                        '角色“' +
                            this.selectedRoles[i].roleName +
                            '”和机构不属于同一个集团，是否继续？'
                    ) === false
                ) {
                    return;
                }
            }
        }
        $('#btnSubmitConfig').prop('disabled', true);
        $('#btnPrevious').prop('disabled', true);
        $('#btnSubmitConfig').val('正在保存中，请稍后……');
        isSubmitingConfig = true;
        const userIds = [];
        for (let i = 0; i < this.selectedUsers.length; i++) {
            userIds.push(this.selectedUsers[i].userId);
        }
        const orgId = this.selectedOrg.orgId;
        const positionId = this.selectedPosition.positionId;
        const roleIds = [];
        for (let i = 0; i < this.selectedRoles.length; i++) {
            roleIds.push(this.selectedRoles[i].roleId);
        }
        const data = {
            userIds: userIds,
            orgId: orgId,
            positionId: positionId,
            roleIds: roleIds
        };
        const that = this;
        $.ajax({
            url: '/user/back/config/save',
            type: 'PUT',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(data), // 数据 必须是字符串
            dataType: 'json', // 期望返回类型 json, xml
            processData: false, // 防止 data 被预处理
            success: function(rt) {
                if (rt.status === 200) {
                    alert('保存成功！');
                    that.selectedUsers = [];
                    that.selectedOrg = null;
                    that.selectedPosition = null;
                    that.selectedRoles = [];
                } else {
                    alert(rt.message);
                }
                $('#btnSubmitConfig').prop('disabled', false);
                $('#btnPrevious').prop('disabled', false);
                $('#btnSubmitConfig').val('确定');
                isSubmitingConfig = false;
            },
            error: function(rt) {
                alert(
                    rt.responseJSON.error == null
                        ? rt.responseJSON.message
                        : rt.responseJSON.error
                );
                $('#btnSubmitConfig').prop('disabled', false);
                $('#btnPrevious').prop('disabled', false);
                $('#btnSubmitConfig').val('确定');
                isSubmitingConfig = false;
            }
        });
    }
    loadOriginConfig() {
        if (this.selectedUsers.length === 0) {
            alert('请选择需要配置的帐号');
            return;
        }
        if (!this.selectedOrg) {
            alert('请选择指派机构');
            return;
        }
        if (!this.selectedPosition) {
            alert('选择指派职位');
            return;
        }
        $('#btnLoadConfig').prop('disabled', true);
        $('#btnLoadConfig').val('正在读取数据……');
        let userIds = '';
        for (let i = 0; i < this.selectedUsers.length; i++) {
            userIds += this.selectedUsers[i].userId + ',';
        }
        userIds.substring(0, userIds.length - 1);
        const orgId = this.selectedOrg.orgId;
        const positionId = this.selectedPosition.positionId;
        const that = this;
        $.ajax({
            url:
                '/user/back/config/load/user-ids-' +
                userIds +
                '/org-' +
                orgId +
                '/position-' +
                positionId,
            type: 'GET',
            contentType: 'application/json; charset=UTF-8',
            dataType: 'json', // 期望返回类型 json, xml
            success: function(rt) {
                if (rt.status === 200) {
                    alert('加载成功！');
                    that.selectedRoles = rt.roles;
                } else {
                    alert(rt.message);
                }
                $('#btnLoadConfig').prop('disabled', false);
                $('#btnLoadConfig').val('加载原始配置');
            },
            error: function(rt) {
                alert(
                    rt.responseJSON.error == null
                        ? rt.responseJSON.message
                        : rt.responseJSON.error
                );
                $('#btnLoadConfig').prop('disabled', false);
                $('#btnLoadConfig').val('加载原始配置');
            }
        });
    }
}
